import { createRouter, createWebHistory } from 'vue-router'
import MainLayout from '../views/MainLayout.vue'  // 修改为相对路径
import Profile from '../views/Profile.vue'  // 新增导入

const routes = [
  {

    path: '/',
    component: MainLayout,
    children: [
      {
        path: '/landlord/my-house',
        name: 'my-houses',
        component: () => import('../views/landlord/MyHouse.vue')
      },

      {
        path: '/landlord/add-house',
        name: 'AddHouses',
        component: () => import('../views/landlord/AddHouses.vue')
      },

      {
        path: 'landlord/upload-images/:houseId', // 图片上传（动态路由参数）
        name: 'LandlordUploadImages',
        component: () => import('../views/landlord/UploadHouseImages.vue')
      },

      {
        path: '/houses/:houseId', // 房源详情
        name: 'HouseDetail',
        component: () => import('../views/landlord/HouseDetail.vue')
      },

      {
        path: '/landlord/applications',
        component: () => import('../views/landlord/Applications.vue')
      },
      {
        path: '/landlord/orders',
        component: () => import('../views/landlord/Orders.vue')
      },
      {
        path: '/profile',
        component: Profile
      },
      {
        path: '/rent/show',
        name: 'show',
        component: () => import('../views/rent/show.vue')
      },

      {
        path: '/rent/RhouseDetail/:houseid',
        name: 'RhouseDetail',
        component: () => import('../views/rent/RhouseDetail.vue')
      },

      {
        path: '/rent/OrderDetail/:orderId',
        name: 'order-detail',
        component: () => import('../views/rent/OrderDetail.vue')
      },

      {
        path: '/rent/MyOrder',
        name: 'my-order',
        component: () => import('../views/rent/MyOrder.vue')
      },
    ]
  },
  {
    path: '/home',
    component: () => import('../views/WelcomePage.vue')
  },
  {
    path: '/test',
    component: () => import('../views/Test.vue')
  },
  {
    path: '/welcome',
    name: 'welcome',
    component: () => import('../views/user/loginPage.vue'),
    children: [
      {
        path: 'login',
        name: 'welcome-login',
        component: () => import('../components/user/loginForm.vue')
      },
      {
        path: 'register',
        name: 'welcome-register',
        component: () => import('../components/user/registerForm.vue')
      },
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 需要登录的页面路径
  const authPages = ['/landlord/orders', '/landlord/houses', '/landlord/applications'];
  const isAuthPage = authPages.includes(to.path);
  const isLoggedIn = !!sessionStorage.getItem('Authorization');
  if (isAuthPage && !isLoggedIn) {
    next('/welcome/login');
  } else {
    next();
  }
});

export default router